#! /usr/bin/perl

#-----------------------------------------------------------
# Send client a message to confirm received file.
#
# Usage:
# 	 $script_name   $payorintel_file_name
#
# Exit status:
#    0 -- Ok
#    1 -- No filename for input
#    2 -- Database connection error
#-----------------------------------------------------------

use strict;
use DBI;
use DBD::Pg  qw(:pg_types);
use Net::Domain  qw(hostname);
use MIME::Lite;
use Getopt::Std;


our $opt_t;
our	$db_pwd_file = "$ENV{MLPROD_HOME}/config/.mlprivate.cfg";


#------------------------------------------------------------
# email_file( email_addrs, file)
#   It will send encrypted mail to every receiver
#------------------------------------------------------------
sub email_file($$) {
	my $addrs = shift;
	my $file  = shift;

	my @emails = split( /[,;]/, $addrs);
	return if @emails == 0;
	my $receiver = shift @emails ;
	my $cc = (@emails > 0)?  join ',', @emails : "";

	my $msg = MIME::Lite->new(
		From	=> 'support@medlytix.com',	
		To		=> $receiver,
		Bcc  	=> $cc,
		Subject => 'Medlytix received new file',
		Data	=> "Received file : $file. No reply please."
		);
	return if ! $msg;

	$msg->send('smtp', 'mailhost', Timeout => 600);
}


#-----------------------------------------------------
# Get db user's passwd from some hidden file
#-----------------------------------------------------
sub get_db_passwd($$) {
	my $dbnm = shift;
	my $dbusr = shift;

	open(PAS, "<$db_pwd_file") or return;
	my $passwd;
	while( my $line = <PAS> ) {
		if ($line =~ /^db:$dbnm:$dbusr/i ) {
			$passwd = $line;
			chomp $passwd;
			$passwd =~ s/^.*pwd\s+//;
			last;
		}
	}
	close(PAS);
	$passwd;
}



#---------------------------------------------------
# connect_db( dbname, db_user, password )
#--------------------------------------------------
sub connect_db($$$) {
    my $db_name = shift;   
	my $db_user = shift;
	my $passwd = shift;
    my $dbh = DBI->connect( "DBI:Pg:dbname=$db_name;host=$ENV{PGHOST}", 
								$db_user, $passwd );
    if (!ref $dbh or !$dbh->ping ) { 
		return undef ;
	}
    $dbh->{AutoCommit} = 0;
    $dbh;
}




#-----------------------------------------------------------
# get_client_email(db_handle, cust_id )
#-----------------------------------------------------------
sub get_client_email($$)
{
	my $dbh 		= shift;
	my $cust_id 	= shift;
	my $email;

	my $sql = qq( 
			select email_part1
			from insurance0_output_t 
			where );

	$sql .= " cust_id = $cust_id limit 1";
	my $sth = $dbh->prepare( $sql );
	return if ! $sth;
	$sth->execute();
	if( $sth->rows > 0 ) {
	   $email = ($sth->fetchrow_array())[0] ; 
	}
	$sth->finish();
	return $email;
}



sub usage() { 
	my $msg = qq(
	Usage:
	  $0  cust_id  file_name  
		   -- cust_id :	ID of a customer, integer	
		   -- file_name : file just received from client.
	\n);

	print STDERR $msg; 
}


#---------------------------------------------------
# start of the main script
#---------------------------------------------------

getopts('t');

if ( @ARGV < 1 ) { 
	usage(); exit 1;
}

my  $rcvd_file = $ARGV[0];
	$rcvd_file =~ s#^.*/##;

	my $cust_id = $rcvd_file;
	$cust_id =~ s/^.*\d{6}_(\d{6})_*/$1/;
	$cust_id =~ s/^0*//;

	if( ! exists $ENV{'PGHOST'} ) {
		my $host = hostname() ;
		my $alias = (gethostbyname($host))[1];
		my @aliases = split(/\s+/, $alias);
		my @dbhosts = grep(/^hdb-/, @aliases);
		if ( @dbhosts > 0 ) {
			$ENV{'PGHOST'} = shift @dbhosts;
		} else {
			$ENV{'PGHOST'} = shift @aliases;
		}
	}

	#-------------------------------------
	# Find out client email  
	#------------------------------------
	my $g_dbschema = "payorintel";
	my $g_dbbasename="$ENV{USER}" || "mlprod" ;
	my $g_dbname=$g_dbbasename . "_db";
	my $g_dbuser=$g_dbschema . "_" . $g_dbbasename . "_u";
	my $passwd = get_db_passwd($g_dbname , $g_dbuser); 
	my $dbh = connect_db($g_dbname, $g_dbuser, $passwd) ;
	
	if( ! $dbh ) { 
		print STDERR "Error to connect database\n";
		exit 2;
	}

	my $email = get_client_email($dbh, 1);
	$dbh->rollback();
	$dbh->disconnect();

	if( $email =~ /\@/ ) {
		email_file($email, $rcvd_file);
	}

	exit 0;



